import React, { useState, useEffect, lazy, useCallback, useRef } from "react"
import {
  Card,
  Button,
  Table,
  Input,
  Drawer,
  Form,
  Modal,
  Image,
  Space,
} from "antd"
import { ExclamationCircleOutlined } from "@ant-design/icons"

import { getList, insertList, deleteList, getDetail, updateList } from "@/api"
import Icons from "@/utils/icons"
const Btn = lazy(() => import("@/components/linekButton"))
const { confirm } = Modal

export default function Product() {
  const initDetail = {
    title: "",
    tel: "",
    address: "",
    openTime: "",
    tags: "",
    bookingRules: "",
  }
  const [form] = Form.useForm()
  const [pages, setPages] = useState({ page: 1, pageSize: 5 })
  const [searchs, setSearchs] = useState({ title: "" })
  const [totals, setTotal] = useState(0)
  const [dataList, setDataList] = useState([])
  const [loading, setLoading] = useState(false)
  const [open, setOpen] = useState(0)
  const [details, setDetails] = useState(initDetail)
  const [searchIpts, setSearchIpts] = useState("")
  const searchIpt = useRef()

  const columns = [
    {
      title: "名称",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "文化馆主图",
      dataIndex: "picture",
      key: "picture",
      width: 150,
      render: (picture) => (
        <Image
          height={60}
          width={120}
          src={
            picture || "http://106.227.3.119:9991/images/20220819095221019.jpg"
          }
        ></Image>
      ),
    },
    {
      title: "标签",
      dataIndex: "tags",
      key: "tags",
    },
    {
      title: "地址",
      dataIndex: "address",
      key: "address",
    },
    {
      title: "联系电话",
      dataIndex: "tel",
      key: "tel",
      width: 120,
    },
    {
      title: "预约规则",
      dataIndex: "bookingRules",
      key: "bookingRules",
    },
    {
      title: "操作",
      dataIndex: "operation",
      key: "operation",
      width: 150,
      render: (_, record) => {
        return (
          <Space>
            <Btn onClick={() => updates(record.id)}>编辑</Btn>
            <Btn onClick={() => deletes(record.id)}>删除</Btn>
          </Space>
        )
      },
    },
  ]

  const pagination = {
    current: pages.page,
    pageSize: pages.pageSize,
    total: parseInt(totals),
    showSizeChanger: true,
    pageSizeOptions: [5, 10, 20, 50, 100],
    onChange: (v, t) => {
      if (t !== pages.pageSize) v = 1
      setPages({ ...pages, page: v, pageSize: t })
    },
  }

  const getDataList = useCallback(async () => {
    setLoading(true)
    try {
      const { data: res } = await getList({ ...pages, ...searchs })
      const { records, total } = res
      setTotal(total)
      setDataList(records)
      setLoading(false)
    } catch (error) {
      setLoading(false)
    }
  }, [pages, searchs])

  const deletes = (id) => {
    confirm({
      title: "是否删除？",
      icon: <ExclamationCircleOutlined />,
      centered: true,
      cancelText: "取消",
      okText: "确定",
      onOk() {
        deleteList(id).then((res) => {
          React.$message(res.data)
          getDataList()
        })
      },
      onCancel() {
        React.$message("未删除", "warn")
      },
    })
  }
  const updates = (id) => {
    getDetail(id).then((res) => {
      setDetails(res.data)
      setOpen(2)
      if (form) {
        form.setFieldsValue(res.data)
      }
    })
  }
  const onFinish = async (values) => {
    const res =
      open === 1
        ? await insertList(values)
        : await updateList({ ...details, ...values })
    onClose()
    React.$message(res.data)
    getDataList()
  }
  const onClose = () => {
    form.resetFields()
    setDetails(initDetail)
    setOpen(0)
  }
  const onSearch = () => {
    setPages({ ...pages, page: 1 })
    setSearchs({ title: searchIpt.current.input.value })
  }
  const onRemoves = () => {
    setSearchIpts("")
    setSearchs({ title: "" })
  }
  useEffect(() => {
    getDataList()
    return () => {}
  }, [pages, getDataList])

  return (
    <div>
      <Card
        title={
          <div>
            <span>文化馆名称：</span>
            <Input
              ref={searchIpt}
              value={searchIpts}
              style={{ width: "200px", margin: "0 10px" }}
              placeholder="请输入文化馆名称"
              onChange={(e) => {
                setSearchIpts(e.target.value)
              }}
            />
            <Space>
              <Button type="primary" onClick={onSearch}>
                搜索
              </Button>
              <Button type="primary" onClick={onRemoves}>
                重置
              </Button>
            </Space>
          </div>
        }
        extra={
          <Button
            type="primary"
            onClick={() => {
              setOpen(1)
              form.setFieldsValue(details)
            }}
          >
            <Icons type="icon-add" />
            新增
          </Button>
        }
      >
        <Table
          rowKey="id"
          dataSource={dataList}
          loading={loading}
          columns={columns.map((item) => {
            const fun = () => ({
              style: {
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
              },
            })
            item.onCell = fun
            return item
          })}
          pagination={pagination}
        ></Table>
      </Card>
      <Drawer
        title={open === 1 ? "新增" : "编辑"}
        width="40%"
        placement="right"
        key={() => open + "-" + details}
        onClose={onClose}
        visible={open !== 0}
      >
        {open === 1 || details ? (
          <Form
            initialValues={details}
            form={form}
            layout="horizontal"
            onFinish={onFinish}
            className="forms"
            labelCol={{ style: { width: "7em" } }}
            labelAlign="left"
          >
            <Form.Item
              label="文化馆名称"
              name="title"
              required
              key={details.title || ""}
              rules={[
                {
                  required: true,
                  message: "文化馆名称不能为空",
                },
              ]}
            >
              <Input key={details.title} placeholder="请输入文化馆名称" />
            </Form.Item>
            <Form.Item
              label="联系电话"
              name="tel"
              rules={[
                {
                  required: true,
                  message: "联系电话不能为空",
                },
              ]}
              required
            >
              <Input key={details.tel} placeholder="请输入联系电话" />
            </Form.Item>
            <Form.Item
              label="详细地址"
              rules={[
                {
                  required: true,
                  message: "详细地址不能为空",
                },
              ]}
              name="address"
              required
            >
              <Input key={details.address} placeholder="请输入详细地址" />
            </Form.Item>
            <Form.Item
              label="开放时间"
              rules={[
                {
                  required: true,
                  message: "开放时间不能为空",
                },
              ]}
              name="openTime"
              required
            >
              <Input
                key={details.openTime}
                placeholder="请输入开放时间(周一至周五 8:00~17:00)"
              />
            </Form.Item>
            <Form.Item
              label="标签"
              rules={[
                {
                  required: true,
                  message: "标签不能为空",
                },
              ]}
              name="tags"
              required
            >
              <Input
                key={details.tags}
                placeholder="请输入标签(标签之间用','隔开')"
              />
            </Form.Item>
            <Form.Item
              label="预约规则"
              rules={[
                {
                  required: true,
                  message: "预约规则不能为空",
                },
              ]}
              name="bookingRules"
              required
            >
              <Input key={details.bookingRules} placeholder="请输入预约规则" />
            </Form.Item>
            <Form.Item>
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <Button htmlType="submit" type="primary">
                  提交
                </Button>
                <Button onClick={onClose}>取消</Button>
              </div>
            </Form.Item>
          </Form>
        ) : null}
      </Drawer>
    </div>
  )
}
